//
//  EVEAPISkillQueue.m
//  EVE Mac Suite
//
//  Created by Vadim Lozko on 4/9/09.
//  Copyright 2009 __Vadim__CompanyName__. All rights reserved.
//

#import "EVEAPISkillQueue.h"
#import "EVEAPICoreDataController.h"
#import "EMSSkillTrainingInfo.h"
#import "EVECDCharacter.h"
#import "EVECDQueueItem.h"
#import "EVECDLearnedSkill.h"

@implementation EVEAPISkillQueue

-(NSString*)xmlStorePath
{
	return [[super xmlStorePath] stringByAppendingString:@" - SkillQueue.xml"];
}

-(NSString*)APIDocumentType
{
	return CHARACTER_SKILL_QUEUE_API_TYPE;
}

-(void)updateCoreDataStore
{
	NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
	//[EVECDContext lock];
	//[[EVEAPICoreDataController coreDataController] performSelectorOnMainThread:@selector(lockContext) withObject:nil waitUntilDone:YES];
#ifdef DEBUG
	NSLog(@"Updating skill Queue for %@", [self charName]);
#endif
	_character = [(EVECDCharacter*)[EVECDContext fetchObjectForEntityName:@"EVECDCharacter" 
															withPredicate:@"name like %@", [self charName]] retain];
	NSSet* queueItems = _character.queuedSkills;

	for(EVECDQueueItem* queueItem in queueItems)
	{
		[queueItem.queuedSkill removePartOfQueueItemObject:queueItem];
		[EVECDContext deleteObject:queueItem];
	}
	[[EVEAPICoreDataController coreDataController] saveData];
	
	NSPredicate* learnedSkillsPredicate = [NSPredicate predicateWithFormat:@"partOfLearnedGroup.learnedBy.name like %@", _character.name];
	_learnedSkills = [[EVECDContext fetchObjectsForEntityName:@"EVECDLearnedSkill" withPredicate:learnedSkillsPredicate] retain];
	NSXMLParser* parser = [[NSXMLParser alloc] initWithData:[xmlDoc XMLData]];
	parser.delegate = self;
	[parser parse];
	[_character release];
	[[EVEAPICoreDataController coreDataController] saveData];
	//[EVECDContext unlock];
	//[[EVEAPICoreDataController coreDataController] performSelectorOnMainThread:@selector(unlockContext) withObject:nil waitUntilDone:YES];
#ifdef DEBUG
	NSLog(@"Finished updating character skill queue for %@", [self charName]);
#endif
	//[self performSelectorOnMainThread:@selector(updateDidFinish:) withObject:(NSNumber*)kCFBooleanTrue waitUntilDone:NO];
	[self updateDidFinish:(NSNumber*)kCFBooleanTrue];
	[pool release];
}

-(void)verifyCoreDataStore
{
	//[NSThread detachNewThreadSelector:@selector(updateCoreDataStore) toTarget:self withObject:nil];
	[self updateCoreDataStore];
}

//Relying on character sheet's update timer
-(void) startUpdateTimer{}

-(void)updateDidFinish:(NSNumber*)success 
{
	if(_skillInTraining)
	{
		NSDictionary* userInfoDict = [NSDictionary dictionaryWithObjectsAndKeys:[self charName], CHAR_INFO_DICT_NAME, 
									  success, NOTIFICATION_SUCCESS_UPDATE_KEY, nil];
		[[NSNotificationCenter defaultCenter] postNotificationName:[self APIDocumentType] object:_skillInTraining userInfo:userInfoDict];
		[_skillInTraining release];
		_skillInTraining = nil;
	} else {
		[super updateDidFinish:success];
	}
	
}

@end

@implementation EVEAPISkillQueue (ParseDelegate)

-(void)parser:(NSXMLParser*)parser 
didStartElement:(NSString*)elementName
 namespaceURI:(NSString*)namespaceURI 
qualifiedName:(NSString*)qualifiedName 
   attributes:(NSDictionary*)attributeDict
{
	if([elementName isEqualToString:@"row"])
	{
		//[EVECDContext lock];
		NSPredicate* skillIDPredicate = [NSPredicate predicateWithFormat:@"skill.id == %@", 
										 [NSNumber numberWithInt:[[attributeDict objectForKey:@"typeID"] intValue]]];
		EVECDLearnedSkill* learnedSkill = [[_learnedSkills filteredSetUsingPredicate:skillIDPredicate] anyObject];
		int queuePosition = [[attributeDict objectForKey:@"queuePosition"] intValue];
		if(queuePosition == 0)
		{
			learnedSkill.currentlyInTraining = (NSNumber*)kCFBooleanTrue;
			_skillInTraining = [learnedSkill retain];
			NSDate* startDate = [NSDate dateWithString:[[attributeDict objectForKey:@"startTime"] stringByAppendingString:@" +0000"]];
			NSTimeInterval trainingTimeTillNow = [[NSDate date] timeIntervalSinceDate:startDate];
			double skillPointsPerSecond = [EMSSkillTrainingInfo skillPointsPerSecondForSkill:_skillInTraining];
			int accruedSkillPoints = _skillInTraining.skillPointsLearned.intValue + (trainingTimeTillNow * skillPointsPerSecond);
			_skillInTraining.skillPointsLearned = [NSNumber numberWithInt:accruedSkillPoints];
			_skillInTraining.learningStart = [NSDate date];
		}
		EVECDQueueItem* queueItem = [NSEntityDescription insertNewObjectForEntityForName:@"EVECDQueueItem"
																  inManagedObjectContext:EVECDContext];
		queueItem.queuedSkill = learnedSkill;
		queueItem.position = [NSNumber numberWithInt:queuePosition];
		queueItem.queuedFor = _character;
		queueItem.queuedLevel = [NSNumber numberWithInt:[[attributeDict objectForKey:@"level"] intValue]];
		//[EVECDContext unlock];
	}
	self.currentCharacters = @"";
}

- (void)parser:(NSXMLParser*)parser foundCharacters:(NSString*)string
{
	self.currentCharacters = [self.currentCharacters stringByAppendingString:string];
}


-(void)parserDidEndDocument:(NSXMLParser*)parser
{
	[_learnedSkills release];
	[super parserDidEndDocument:parser];
}

@end

